package com.hyt.it.ogt.pj.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hyt.common.apiInfor.ApiResponse;
import com.hyt.core.base.BaseServiceImpl;
import com.hyt.it.ogt.pj.feign.KwClient;
import com.hyt.it.ogt.pj.mapper.SubjectScoreMapper;
import com.hyt.it.ogt.pj.model.entity.Paper;
import com.hyt.it.ogt.pj.model.entity.Student;
import com.hyt.it.ogt.pj.model.entity.Subject;
import com.hyt.it.ogt.pj.model.entity.SubjectScore;
import com.hyt.it.ogt.pj.model.vo.ObjectiveScoreVO;
import com.hyt.it.ogt.pj.model.vo.PaperSubjectiveScore;
import com.hyt.it.ogt.pj.model.vo.StudentMarkStatus;
import com.hyt.it.ogt.pj.model.vo.StudentSubjectSubjectiveScore;
import com.hyt.it.ogt.pj.service.*;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 总分表 服务实现类
 * </p>
 *
 * @author qiaozj
 * @since 2020-07-09
 */
@Service
public class SubjectScoreServiceImpl extends BaseServiceImpl<SubjectScoreMapper, SubjectScore> implements ISubjectScoreService {

    protected Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private SubjectScoreMapper subjectScoreMapper;

    @Autowired
    private IPaperService paperService;

    @Autowired
    private IStudentService iStudentService;

    @Autowired
    private ISubjectScoreService iSubjectScoreService;

    @Autowired
    private IPieceService iPieceService;

    @Autowired
    private IPieceScoreService iPieceScoreService;

    @Autowired
    private KwClient kwClient;

    @Override
    public SubjectScore getStudentSubjectScore(String projectId, String subjectId, String encodeId) {
        SubjectScore subjectScore = subjectScoreMapper.getStudentSubjectScore(projectId, subjectId, encodeId);
        return subjectScore;
    }

    /**
     * 获取某项目或者某科目下已完成评卷数量
     *
     * @param projectId 评卷项目id
     * @param subjectId 评卷科目id
     * @return 返回数量
     */
    @Override
    public Integer getMarkNum(String projectId, String subjectId) {
        return subjectScoreMapper.getMarkNum(projectId, subjectId);
    }

    /**
     * 初始化客观分，若有准考证号，则表示为增量添加，若没有则为全量添加
     *
     * @param projectId 评卷项目id
     * @param admission 准考证号
     */
    @Override
    public void initKgScore(String projectId, String admission) {
        // 从考务获取客观题分数作为总分数的基础分
        ApiResponse<List<ObjectiveScoreVO>> res = kwClient.getKgScore(projectId, admission);
        logger.info("## 拉取到的评卷学生主观题得分数据:{}", JSONObject.toJSONString(res));
        List<ObjectiveScoreVO> objectiveScores = new ArrayList<ObjectiveScoreVO>();
        if (null != res && CollectionUtils.isNotEmpty(res.getData())) {
            objectiveScores = res.getData();
        }
        List<SubjectScore> subjectScoreList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(objectiveScores)) {
            for (ObjectiveScoreVO objectiveScoreVO : objectiveScores) {
                SubjectScore subjectScore = new SubjectScore();
                subjectScore.setProjectId(objectiveScoreVO.getProjectId());
                subjectScore.setSubjectId(objectiveScoreVO.getSubjectId());
                subjectScore.setAdmissionNum(objectiveScoreVO.getAdmissionNum());
                subjectScore.setEncodeId(objectiveScoreVO.getAdmissionNum());
                subjectScore.setObjectiveScore(objectiveScoreVO.getKgScore());
                subjectScore.setTotalScore(objectiveScoreVO.getKgScore());
                subjectScoreList.add(subjectScore);
            }
            saveBatch(subjectScoreList);
        }
    }

    /**
     * 根据评卷项目id 和准考证号查询考生评卷状态，在全卷评卷模式下，有科目主观分代码已经评完，没有表示未评
     *
     * @param projectId    评卷项目id
     * @param admissionNum 准考证号
     * @return 返回考生评卷状态数据
     */
    @Override
    public StudentMarkStatus selectStudentMarkStatus(String projectId, String admissionNum) {
        StudentMarkStatus result = new StudentMarkStatus();
        // 先设置个默认值
        result.setMarkStatus(true);
        result.setSubjectiveScore(new BigDecimal(0));
        // 查询组装数据
        List<Student> studentList = iStudentService.lambdaQuery()
                .eq(Student::getProjectId, projectId)
                .eq(Student::getAdmissionNum, admissionNum)
                .eq(Student::getDelFlag, false)
                .list();

        List<SubjectScore> subjectScores = iSubjectScoreService.lambdaQuery()
                .eq(SubjectScore::getProjectId, projectId)
                .eq(SubjectScore::getEncodeId, admissionNum)
                .eq(SubjectScore::getDelFlag, false)
                .list();


        Map<String, SubjectScore> paperScoreMap = new HashMap<>();
        for (SubjectScore subjectScore : subjectScores) {
            paperScoreMap.put(subjectScore.getSubjectId(), subjectScore);
        }
        List<PaperSubjectiveScore> paperSubjectiveScores = new ArrayList<>();
        for (Student student : studentList) {
            // 获取考生数据
            String paperId = student.getPaperId();
            String packageId = student.getPackageId();
            Integer paperVersion = student.getPaperVersion();
            String subjectId = student.getSubjectId();
            PaperSubjectiveScore paperSubjectiveScore = new PaperSubjectiveScore();

            if (null == paperScoreMap.get(subjectId)) {
                result.setMarkStatus(false);
            } else {
                if (null != paperScoreMap.get(subjectId).getSubjectiveScore() && null != paperScoreMap.get(subjectId).getChildSubjectiveScore()
                        && !paperScoreMap.get(subjectId).getSubjectiveScore().equals(paperScoreMap.get(subjectId).getChildSubjectiveScore())) {
                    result.setSubjectiveScore(result.getSubjectiveScore().add(paperScoreMap.get(subjectId).getChildSubjectiveScore()));
                    paperSubjectiveScore.setSubjectiveScore(paperScoreMap.get(subjectId).getChildSubjectiveScore());
                } else {
                    result.setSubjectiveScore(result.getSubjectiveScore().add(null == paperScoreMap.get(subjectId).getSubjectiveScore() ? BigDecimal.ZERO : paperScoreMap.get(subjectId).getSubjectiveScore()));
                    paperSubjectiveScore.setSubjectiveScore(paperScoreMap.get(subjectId).getSubjectiveScore());
                }
            }
            paperSubjectiveScores.add(paperSubjectiveScore);

            // 设置试卷id，试卷版本，现根据packageId找

            Paper paper = paperService.getBaseMapper().selectOne(
                    new LambdaQueryWrapper<Paper>()
                            .eq(Paper::getProjectId, projectId)
                            .eq(Paper::getSubjectId, subjectId)
                            .eq(Paper::getPackageId, packageId)
                            .eq(Paper::getPaperVersion, paperVersion));


            if (null != paper) {
                // 试卷包情况
                paperSubjectiveScore.setPaperId(paper.getPaperId());
                paperSubjectiveScore.setPaperVersion(paper.getPaperVersion());
            } else {
                // 试卷情况
                Paper paper1 = paperService.getBaseMapper().selectById(paperId);
                if (null == paper1) {
                    // 现考现评的存的是paperId
                    paper1 = paperService.getBaseMapper().selectOne(
                            new LambdaQueryWrapper<Paper>()
                                    .eq(Paper::getSubjectId, subjectId)
                                    .eq(Paper::getProjectId, projectId)
                                    .eq(Paper::getId, paperId)
                                    .eq(Paper::getPaperVersion, paperVersion));
                }
                if (null != paper1) {
                    paperSubjectiveScore.setPaperId(paper1.getPaperId());
                    paperSubjectiveScore.setPaperVersion(paper1.getPaperVersion());
                }
            }
        }

        // 分数列表为空返回未评卷
        if (CollectionUtils.isEmpty(paperSubjectiveScores)) {
            result.setMarkStatus(false);
        }

        result.setPaperSubjectiveScores(paperSubjectiveScores);
        return result;
    }


    /**
     * 根据评卷项目id 和准考证号查询考生评卷状态，在全卷评卷模式下，有科目主观分代码已经评完，没有表示未评
     *
     * @param projectId    评卷项目id
     * @param admissionNum 准考证号
     * @return 返回考生评卷状态数据
     */
    @Override
    public List<StudentSubjectSubjectiveScore> selectStudentsMarkStatus(String projectId, List<String> admissionNums) {
        List<StudentSubjectSubjectiveScore> results = new ArrayList<>();


        List<SubjectScore> subjectScores = subjectScoreMapper.getStudentSubjectiveScoreByAdmissionNum(projectId, admissionNums);

        Map<String, SubjectScore> paperScoreMap = new HashMap<>();
        for (SubjectScore subjectScore : subjectScores) {
            paperScoreMap.put(subjectScore.getAdmissionNum(), subjectScore);
        }
        for (String admissionNum : admissionNums) {
            StudentSubjectSubjectiveScore studentSubjectSubjectiveScore = new StudentSubjectSubjectiveScore();
            studentSubjectSubjectiveScore.setProjectId(projectId);
            studentSubjectSubjectiveScore.setAdmissionNum(admissionNum);
            SubjectScore subjectScore = paperScoreMap.get(admissionNum);
            if (null != subjectScore) {
                studentSubjectSubjectiveScore.setSubjectiveScore(subjectScore.getSubjectiveScore());
            }
            results.add(studentSubjectSubjectiveScore);
        }
        return results;
    }


    @Override
    public Map<String, StudentMarkStatus> selectAllStudentMarkStatus(String projectId) {
        List<Student> studentList = iStudentService.lambdaQuery().eq(Student::getProjectId, projectId).list();
        Map<String, StudentMarkStatus> map = new HashMap<>();
        for (Student student : studentList) {
            map.put(student.getAdmissionNum(), selectStudentMarkStatus(projectId, student.getAdmissionNum()));
        }
        return map;
    }

    @Override
    public List<SubjectScore> getStudentSubjectiveScoreByAdmissionNum(String projectId, List<String> admissionNums) {
        return subjectScoreMapper.getStudentSubjectiveScoreByAdmissionNum(projectId, admissionNums);
    }

    @Override
    public void saveObjectiveScore(String projectId, List<ObjectiveScoreVO> objectiveScoreVOs, List<Subject> subjects) {
        List<String> subjectiveSubjectIds = new ArrayList<String>();
        if (com.baomidou.mybatisplus.core.toolkit.CollectionUtils.isNotEmpty(subjects)) {
            for (Subject subject : subjects) {
                subjectiveSubjectIds.add(subject.getSubjectId());
            }
        }
        if (com.baomidou.mybatisplus.core.toolkit.CollectionUtils.isNotEmpty(objectiveScoreVOs)) {
            List<SubjectScore> subjectScoreList = new ArrayList<>();
            for (ObjectiveScoreVO objectiveScoreVO : objectiveScoreVOs) {
                if (subjectiveSubjectIds.contains(objectiveScoreVO.getSubjectId())) {
                    SubjectScore subjectScore = new SubjectScore();
                    subjectScore.setProjectId(objectiveScoreVO.getProjectId());
                    subjectScore.setSubjectId(objectiveScoreVO.getSubjectId());
                    subjectScore.setAdmissionNum(objectiveScoreVO.getAdmissionNum());
                    subjectScore.setEncodeId(objectiveScoreVO.getAdmissionNum());
                    subjectScore.setObjectiveScore(objectiveScoreVO.getKgScore());
                    subjectScore.setTotalScore(objectiveScoreVO.getKgScore());
                    subjectScoreList.add(subjectScore);
                }
            }
            if (com.baomidou.mybatisplus.core.toolkit.CollectionUtils.isNotEmpty(subjectScoreList)) {
                saveBatch(subjectScoreList);
            }
        }
    }
}
